package com.kingyea.mobilepolice.apimanage.timingtask;

import com.kingyea.mobilepolice.apimanage.serviceinfo.dao.ServiceInfoMapper;
import com.kingyea.mobilepolice.apimanage.utils.GlobalVar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Component
@Transactional
public class RequesterCountTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequesterCountTask.class);

    @Resource
    private ServiceInfoMapper serviceInfoMapper;

    @Value("${kingyea.mobilepolice.inside}")
    private Integer inside;

    @PostConstruct
    public void initTask() {
        if (inside.intValue() == GlobalVar.insideNei) {
            ScheduledExecutorService syncToeknServer4wai = Executors.newSingleThreadScheduledExecutor();
            ScheduledFuture<?> scheduledFuture = syncToeknServer4wai.scheduleWithFixedDelay(() -> {
                try {
                    createViewData();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }, 20, 60 * 30, TimeUnit.SECONDS);
        }
    }


    /**
     * 创建统计视图，用于加速统计查询
     */
//    @Scheduon = "0 */10 * * * ?")
    public void createViewData() throws Exception {
        LOGGER.info("开始获取创建视图语句，请稍等....");
        String sql = loadingSql();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("_sql", sql);
        LOGGER.info("开始获取创建视图....");
        serviceInfoMapper.requesterCountTask(map);
        LOGGER.info("创建视图成功！");
    }

    private String loadingSql() throws Exception {
        StringBuffer str = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(RequesterCountTask.class.getResourceAsStream("/requesterCount.sql")));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                str = str.append(" " + tempString);
                line++;
            }
            reader.close();
        } catch (Exception e) {
            LOGGER.error("创建视图失败！");
            e.printStackTrace();
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e1) {
                }
            }
        }
        return str.toString();
    }


}
